package top.lingkang.potatoserver.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lingkang.config.FinalContextHolder;
import top.lingkang.potatoserver.constants.HttpConstants;
import top.lingkang.potatoserver.dto.ResponseResult;
import top.lingkang.potatoserver.entity.User;
import top.lingkang.potatoserver.service.UserService;
import top.lingkang.potatoserver.vo.UserInfoVo;
import top.lingkang.session.FinalSession;
import top.lingkang.utils.FinalPasswordUtils;

/**
 * @author lingkang
 * @date 2021/9/19 0:23
 * @description
 */
@RequestMapping("/account")
@RestController
public class AccountController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login_token")
    public ResponseResult login_token(String token) {
        FinalSession finalSession = FinalContextHolder.getFinalSession(token);
        if (finalSession != null) {
            // 登录
            User user = userService.getUserById(Integer.valueOf(finalSession.getId()));
            FinalSession login = FinalContextHolder.login(String.valueOf(user.getId()));
            UserInfoVo infoVo = new UserInfoVo();
            BeanUtil.copyProperties(user, infoVo);
            JSONObject json = new JSONObject();
            json.put("token", login.getToken());
            json.put("info", infoVo);
            return new ResponseResult(HttpConstants.OK, json);
        }
        return new ResponseResult(HttpConstants.FAIL, "登录失败！");
    }

    @RequestMapping("/login")
    public ResponseResult login(String username, String password) {
        Assert.notEmpty(username, "账号不能为空！");
        Assert.notEmpty(password, "密码不能为空！");
        User user = userService.getUser(username);
        Assert.notNull(user, "账号不存在！");
        String pwd = FinalPasswordUtils.base64Encoder(password);
        Assert.isTrue(user.getPassword().equals(pwd), "密码错误！");

        // 登录
        FinalSession login = FinalContextHolder.login(String.valueOf(user.getId()));
        UserInfoVo infoVo = new UserInfoVo();
        BeanUtil.copyProperties(user, infoVo);
        JSONObject json = new JSONObject();
        json.put("token", login.getToken());
        json.put("info", infoVo);
        return new ResponseResult(HttpConstants.OK, json);
    }

    @RequestMapping("check_token")
    public ResponseResult check_token() {
        return new ResponseResult(HttpConstants.OK, "OK", FinalContextHolder.getSessionExpire());
    }
}
